﻿namespace com.net.p8583.utils
{
    using System;
    using System.Globalization;
    using System.Text;

    public class HexUtils
    {
        public static string byteToHexStr(byte[] bytes)
        {
            string str = string.Empty;
            if (bytes != null)
            {
                for (int i = 0; i < bytes.Length; i++)
                {
                    str = str + bytes[i].ToString("X2");
                }
            }
            return str;
        }

        public static byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", string.Empty);
            if ((hexString.Length % 2) != 0)
            {
                hexString = hexString + " ";
            }
            byte[] buffer = new byte[hexString.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10);
            }
            return buffer;
        }

        public static string ToHex(string s, string charset, bool fenge)
        {
            if ((s.Length % 2) != 0)
            {
                s = s + " ";
            }
            byte[] bytes = Encoding.GetEncoding(charset).GetBytes(s);
            string str = string.Empty;
            for (int i = 0; i < bytes.Length; i++)
            {
                str = str + string.Format("{0:X}", bytes[i]);
                if (fenge && (i != (bytes.Length - 1)))
                {
                    str = str + string.Format("{0}", ",");
                }
            }
            return str.ToLower();
        }

        public static string UnHex(string hex, string charset)
        {
            if (hex == null)
            {
                throw new ArgumentNullException("hex");
            }
            hex = hex.Replace(",", string.Empty);
            hex = hex.Replace("/n", string.Empty);
            hex = hex.Replace("//", string.Empty);
            hex = hex.Replace(" ", string.Empty);
            if ((hex.Length % 2) != 0)
            {
                hex = hex + "20";
            }
            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2), NumberStyles.HexNumber);
                }
                catch
                {
                    throw new ArgumentException("hex is not a valid hex number!", "hex");
                }
            }
            return Encoding.GetEncoding(charset).GetString(bytes);
        }
    }
}

